package online.xuping.thousandsOfWorlds.common.importexcel;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.util.Set;

/**
 * EasyExcelValidHelper 类是 excel输入校验类
 *
 * @author dongyinggang
 * @date 2022-01-18 11:30
 **/
public class EasyExcelValidHelper {

    private static final Validator VALIDATOR = Validation.buildDefaultValidatorFactory().getValidator();

    /**
     * validateEntity 方法是 校验对象合法性
     *
     * @param obj 校验对象
     * @return 校验结果
     * @author dongyinggang
     * @date 2022/2/11 9:53
     */
    public static <T> String validateEntity(T obj) {
        StringBuilder result = new StringBuilder();
        Set<ConstraintViolation<T>> set = VALIDATOR.validate(obj, Default.class);
        if (set != null && !set.isEmpty()) {
            for (ConstraintViolation<T> cv : set) {
                //拼接错误信息，包含当前出错数据的标题名字+错误信息
                result.append(cv.getMessage()).append(";");
                //考虑超长存库失败的问题
            }
        }
        return result.toString();
    }
}
